<template>
<div>
  <div class="search">
    <input v-model="keyword" class="search-input" type="text" placeholder="输入城市名或拼音" />
  </div>
  <div class="search-content"
    ref="search"
    v-show="keyword"
  >
    <ul>
      <li class="search-item border-bottom"
      v-for="(item, index) of list"
      :key="index"
      @click="handleCityClick(item.name)"
      >
        {{item.name}}
      </li>
      <li class="search-item border-bottom" v-show="hasNoData">没有找到匹配数据</li>
    </ul>
  </div>
</div>
</template>

<script>
import Bscroll from 'better-scroll';
import { mapMutations } from 'vuex';

export default {
  name: 'CitySearch',
  props: {
    cities: Object,
  },
  data() {
    return {
      keyword: '',
      list: [],
      timer: null,
    };
  },
  computed: {
    hasNoData() {
      return !this.list.length;
    },
  },
  methods: {
    handleCityClick(city) {
      // this.$store.dispatch('changeCity', city); //过程中需要异步调用数据才使用dispatch调用actions
      this.changeCity(city);
      this.$router.push('/');
    },
    ...mapMutations(['changeCity']),
  },
  mounted() {
    this.scroll = new Bscroll(this.$refs.search, { click: true });
  },
  watch: {
    keyword() {
      const that = this;
      if (that.timer) {
        clearTimeout(that.timer);
      }
      if (!that.keyword){
        that.list = [];
        return;
      }
      that.timer = setTimeout(() => {
        const result = [];
        // eslint规则
        const arrs = Object.keys(that.cities);
        for (let i = 0; i < arrs.length; i += 1) {
          // if (JSON.stringify(that.cities[arrs[i]]) !== '{}') {
            that.cities[arrs[i]].forEach((value) => {
              if (value.spell.indexOf(that.keyword) > -1 || value.name.indexOf(that.keyword) > -1) {
                result.push(value);
              }
            });
          // }
        }
        that.list = result;
      }, 100);
    },
  },
};
</script>

<style lang="stylus" scoped>
  @import '~style/varibles.styl'
  .search
    height: 10vw
    line-height: 2vw
    padding:0 1vw
    background : $bgColor
    .search-input
      width: 96vw
      height: 7vw
      line-height : 7vw
      text-align : center
      border-radius: .5vw
      padding:0 1vw
      border: none
      color: #666
  .search-content
    z-index : 1
    overflow : hidden
    position : absolute
    top: 22vw
    left: 0
    bottom: 0
    right: 0
    background : #eeeeee
    .search-item
      line-height: 8vw
      padding-left: 4vw
      background : #fff
      color: #666
</style>
